package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        //记录好友关系：两条好友关系   1-8   8-1
        //1、查询好友关系是否存在
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("friendId").is(friendId)
        );
        if(!mongoTemplate.exists(query, Friend.class)) {
            //2、保存好友关系   userId-friendId
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setId(ObjectId.get());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        query = new Query(
                Criteria.where("userId").is(friendId)
                        .and("friendId").is(userId)
        );
        if(!mongoTemplate.exists(query, Friend.class)) {
            //2、保存好友关系   userId-friendId
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setId(ObjectId.get());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    //分页查询好友列表
    public PageResult findAll(Integer page, Integer pagesize, String keyword, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria).limit(pagesize)
                .skip((page - 1) * pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        return new PageResult(page,pagesize,(int) count,friends);
    }
}
